﻿using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ChiakiYu.Common.Data;
using ChiakiYu.Model.Users;
using ChiakiYu.Service.Authentication;
using ChiakiYu.Service.Users;
using ChiakiYu.Web.ViewModels.Account;

namespace ChiakiYu.Web.Controllers
{
    public partial class AccountController : Controller
    {
        #region 私有字段

        private readonly IUserService _userService;
        private readonly IAuthenticationService _authenticationService;

        #endregion

        #region 构造函数

        public AccountController(IUserService userService, IAuthenticationService authenticationService)
        {
            _userService = userService;
            _authenticationService = authenticationService;
        }

        #endregion

        #region 登录&注销
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public virtual ActionResult Login(string returnUrl = "")
        {
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Request.ApplicationPath;
            }

            if (Request.IsAjaxRequest())
            {
                return PartialView("_LoginInModal", new LoginViewModel
                {
                    ReturnUrl = returnUrl
                });
            }

            return View(
                new LoginViewModel
                {
                    ReturnUrl = returnUrl
                });
        }
        /// <summary>
        /// 处理登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public virtual ActionResult Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
            var password = UserPasswordHelper.MD5(model.PassWord);
            var user = _userService.GetAll().FirstOrDefault(n => (n.UserName == model.UserName || n.Email == model.UserName || n.Mobile == model.UserName) && n.Password == password);

            if (user != null)
            {
                _authenticationService.SignOut();
                _authenticationService.SignIn(user, model.RememberMe);
                if (string.IsNullOrWhiteSpace(model.ReturnUrl))
                {
                    return RedirectToAction(MVC.Channel.Home());
                }
                return Redirect(model.ReturnUrl);
            }
            TempData["StatusMessageData"] = "帐号或密码错误";
            return View(model);

        }
        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public virtual ActionResult Logout()
        {
            _authenticationService.SignOut();
            return RedirectToAction(MVC.Account.Login());
        }

        #endregion

        #region 注册

        /// <summary>
        ///     注册页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public virtual ActionResult Register()
        {
            return View();
        }

        /// <summary>
        ///     处理注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public virtual ActionResult Register(RegisterEditModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
            var user = model.AsUser();

            string message;
            if (!_userService.CheckUserInfo(user, out message))
            {
                TempData["StatusMessageData"] = message;
                return View(model);
            }
            if (_userService.AddUser(user).Id <= 0)
            {
                TempData["StatusMessageData"] = "注册失败，请重试";
                return View(model);
            }
            _authenticationService.SignOut();
            _authenticationService.SignIn(user, false);

            return RedirectToAction(MVC.Channel.Home());
        }

        #endregion
    }
}